package com.rc.evcharger.protocol.ylevcharger.action;

import com.alibaba.fastjson.JSON;
import com.rc.evcharger.common.base.yl.BaseYlBizAction;
import com.rc.evcharger.common.config.RabbitListenerConstant;
import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.common.mq.MqProducer;
import com.rc.evcharger.common.utils.DataUtil;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.protocol.ylevcharger.service.YlChargeMessageService;
import com.rc.evcharger.protocol.ylevcharger.service.YlCommandService;
import com.rc.evcharger.service.elec.ElecGunService;
import com.rc.evcharger.service.elec.ElecPileService;
import com.rc.evcharger.vo.charge.ChargeReportRet;
import com.rc.evcharger.vo.charge.PriceReq;
import com.rc.evcharger.vo.charge.StopChargeReq;
import com.rc.mutievcharger.dto.ylevcharger.terminal.YlTerminalMessage;
import com.rc.mutievcharger.dto.ylevcharger.terminal.req.YlWarnCodeCommandReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * MQ消息处理器，只是这里偏向业务逻辑
 */
@Service
public class YlBizAction implements BaseYlBizAction<YlTerminalMessage> {
    private static Logger logger = LoggerFactory.getLogger(YlBizAction.class);

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private YlCommandService ylCommandService;

    @Autowired
    private YlChargeMessageService ylChargeMessageService;


    @Autowired
    private MqProducer mqProducer;

    /**
     * 处理桩的登录指令A1
     *
     * @param msg
     */
    @Override
    public void login(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        if (elecGun == null) {
            return;
        }

        //TODO 可能需要事务
        ylChargeMessageService.login(elecGun, msg);
        ElecPile elecPile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());

        PriceReq priceReq = new PriceReq(elecPile.getElecPileId());

        String json1 = JSON.toJSONString(msg);
        //登录后延迟1秒,下发设价指令
        mqProducer.sendDelay(RabbitListenerConstant.DOMAIN1_YL_CONTROLL_03_QUEUE, json1, 1000);

        String json = JSON.toJSONString(priceReq);
        //费率下发
        mqProducer.sendDelay(RabbitListenerConstant.DOMAIN1_YL_CONTROLL_4F_04_QUEUE, json, 2000);
    }

    @Override
    public void logout(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        if (elecGun == null) {
            return;
        }

        ////TODO 可能需要事务
        ylChargeMessageService.loginOut(elecGun);
    }

    /**
     * 处理心跳指令（桩）指令
     *
     * @param msg
     * @return
     */
    @Override
    public void hearBeat(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        //防止有心跳却离线
//        if (elecGun == null) {
//            return;
//        }
        if ((SocketConstant.CON0 == elecGun.getStatus())) {
            return;
        }

        //解析得到请求数据
//        YlHearBeatCommondReq result = (YlHearBeatCommondReq) new YlHearBeatCommondReq().getResult(msg.getData());


        //处理枪状态
//        ylChargeMessageService.hearBeat(pile, msg);

    }


    @Override
    public void priceConfirm(YlTerminalMessage msg) {
        ElecPile pile = elecPileService.selectByPileNo(msg.getTerminalId());
        if (pile == null) {
            return;
        }
    }

    @Override
    public String warnCode(YlTerminalMessage msg) {
        ElecPile pile = elecPileService.selectByPileNo(msg.getTerminalId());
        if (pile == null) {
            return "";
        }

        YlWarnCodeCommandReq warnCodeCommandReq = (YlWarnCodeCommandReq) new YlWarnCodeCommandReq().getResult(msg.getData());

        String[] split = warnCodeCommandReq.getWarnCodes().split(DataUtil.SPLIT);
        for (int i = 0; i < split.length; i++) {
            if (split[i].equals("00")) {
                continue;
            }
//            String shWarnCode = YlWarnCode104Enum.getWarnCode104(i + 1, split[i]);
//            logger.warn("YL收到电桩:{} 的告警码:{}", pile.getPileNo(), shWarnCode);
            break;
        }


        return "";
    }

    @Override
    public void priceRequest(YlTerminalMessage msg) {
        //不处理
        //ElecPile pile = elecPileService.selectPileByLogicAddress(msg.getTerminalId());
    }

    @Override
    public void priceConfirem(YlTerminalMessage msg) {
        //不处理
    }

    @Override
    public void chargeDataReport(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        if (elecGun == null) {
            return;
        }
        //处理充电结果
        ChargeReportRet ret = ylChargeMessageService.chargeReport(elecGun, msg);
        if (ret.getStopType() == SocketConstant.CON0) {
            return;
        }

        StopChargeReq stopChargeRequest = new StopChargeReq();
        stopChargeRequest.setStopType(ret.getStopType());
        stopChargeRequest.setCmdCode(SocketConstant.POWER_STOP);
        stopChargeRequest.setOrderNum(ret.getOrderNum());

        //todo 发送停止指令
        if (ret.getStopType() != SocketConstant.STOP_NORMAL_0X0) {

            ylCommandService.query_stop_charge(stopChargeRequest);

            if (ret.getStopType() == SocketConstant.STOP_BALANCE_LOW_0x6) {
                logger.warn("YLchargeReport:该订单：" + ret.getOrderNum() + "余额不足0.5元，,发送充电结束指令");
            } else if (ret.getStopType() == SocketConstant.STOP_ELEC_PRICE_EXCEPTION_0x5) {
                logger.warn("YLchargeReport:该订单：" + ret.getOrderNum() + "电价异常停止,发送充电结束指令");
            } else if (ret.getStopType() == SocketConstant.STOP_IS_ORDER_0XD) {
                logger.warn("YLchargeReport:该订单：" + ret.getOrderNum() + "平台订单已结算,发送充电结束指令");
            }
        }
    }

    @Override
    public void transactonsReport(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        if (elecGun == null) {
            return;
        }

        //结算交易记录
        ylChargeMessageService.chargeBalace(elecGun, msg);

    }

    @Override
    public void startResp(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        if (elecGun == null) {
            return;
        }

        ylChargeMessageService.start(elecGun, msg);
    }

    @Override
    public void stopResp(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        if (elecGun == null) {
            return;
        }
        //处理停止指令
        ylChargeMessageService.stop(elecGun, msg);
    }

    @Override
    public void timing(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        //校时指令下发
         ylCommandService.sendTimingDate(elecGun.getElecGunId());
    }

    @Override
    public void hearBeatSettingRequest(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        //校时指令下发
        ylCommandService.sendTimingDate(elecGun.getElecGunId());
    }

    @Override
    public void balanceUpdateResp(YlTerminalMessage msg) {

    }

}
